<template>
  <div class="yy-page yy-queue-category">
    <div class="yy-page-header">
      <div class="yy-page-header_title">诊室列表</div>
      <div class="yy-page-header_action">
        <el-button  @click="getCategoryList()">刷新</el-button>
        <el-button color="#009688" @click="onOpenDialog()">新增诊室</el-button>
      </div>
    </div>
    <div class="yy-page-data">
       <WidgetTable
           :is-loading="table.isLoading"
           :columns="table.columns"
           :data="table.data"
           :options="table.options"
           :formats="table.formats"
           :paging-data="table.paging"
           :selected-row="selectedRoom"
           @current-change="onSelectRoom"
       ></WidgetTable>
    </div>
  </div>
  <WidgetFormDialog ref="widgetFormDialogRef"
                    :form-fields="dialog.formFields"
                    :model-instance="dialog.modelInstance"
                    :save-api-fun="dialog.saveApiFun"
                    :update-api-fun="dialog.updateApiFun"
                    :option="{
                      businessName: '诊室',
                      formLabelWidth: '60px'
                    }"
                    @edit-callback="onEditCallback"
  />
</template>

<script setup lang="ts">

import {defineEmits, nextTick, onBeforeMount, reactive, ref} from "vue";
import {TableColumn, WidgetFormField} from "@/model/Definition";
import {BaseModel} from "@/model/BaseModel";
import {formatDate} from "@/utils/yayi";
import {QueueRoomModel} from "@/model/QueueRoomModel";
import RoomApi from "@/api/queue/RoomApi";
import WidgetTable from "@/components/widget/WidgetTable.vue";
import WidgetFormDialog from "@/components/widget/WidgetFormDialog.vue";
import {getPatientSourceList} from "@/enums/PatientSourceEnum";
import {PatientSexList} from "@/enums/SexEnum";
import YjCategoryApi from "@/api/queue/YjCategoryApi";

const $emit = defineEmits({
  roomSelected: (room: QueueRoomModel) => room
})

const widgetFormDialogRef = ref()
const selectedRoom = ref()
const listCheckCategory = ref([])

const dialog = reactive<{formFields: WidgetFormField[],modelInstance: BaseModel, saveApiFun: any, updateApiFun: any}>({
  modelInstance: new QueueRoomModel(),
  saveApiFun: RoomApi.saveRegRoom,
  updateApiFun: RoomApi.updateRegRoom,
  formFields: [
    {field: 'name', label: '名称', type: 'text', placeholder: '请输入名称', required: [{required: true, message: '诊室名称不能为空', trigger: 'blur'}]},
    {field: 'location', label: '位置', type: 'textarea', placeholder: '请输入位置'},
    {field: 'orderNo', initVal: 1, label: '排序号', type: 'number', placeholder: '排序号'},
    {field: 'keywords', label: '检索码', type: 'text', placeholder: '请输入检索码'},
    {field: 'patientSource', label: '限制来源', type: 'select', options: getPatientSourceList, config: {select: {clearable: true, multiple: true}}, placeholder: '限制患者来源', formatValFun: (val, field) => val ? val.join(",") : null},
    {field: 'patientSex', label: '限制性别', type: 'select', options: PatientSexList, config: {select: {clearable: true}}, placeholder: '限制患者性别'},
    {field: 'checkCategory', label: '限制检查类别', type: 'select', options: [], config: {select: {clearable: true, multiple: true,}}, placeholder: '限制检查类别', formatValFun: (val, field) => val ? val.join(",") : null},
    {field: 'state', label: '状态', type: 'radioGroup', initVal: 1, options: [{label: '启用', value: 1}, {label: '停用', value: 0}]}
  ]
})

const table = reactive<{
  isLoading: boolean,
  paging: any,
  columns: TableColumn[],
  data: QueueRoomModel[],
  options?: any,
  formats?: any
}>({
  isLoading: false,
  columns: [
    {
      "field":"index",
      "label":"序号",
      "type": "index",
      "showable":true,
      "fixed": 'left',
      "align": 'center',
      "width": 60
    },
    {
      "field":"name",
      "label":"名称",
      "showable":true
    },
    {
      "field":"orderNo",
      "label":"排序号",
      "showable":true,
      "width": 50
    },
    {
      "field":"location",
      "label":"位置",
      "showable":true
    },
    {
      "field":"keywords",
      "label":"检索码",
      "showable":false,
    },
    {
      "field":"updateName",
      "label":"更新用户",
      "showable":false,
      "width": 120
    },
    {
      "field":"updateTime",
      "label":"更新时间",
      "showable":false,
      "width": 160
    },
    {
      "field":"state",
      "label":"状态",
      "showable":true,
      "sortable":false,
      "align": 'center',
      "fixed": 'right',
      "width": 60,
    },
    {
      "field":"action",
      "label":"操作",
      "width": 130,
      "showable":true,
      "sortable":false,
      "align": 'center',
      "fixed": 'right'
    }
  ],
  paging: {
    isPaging: false,
  },
  options: {
    highlight: true
  },
  data: [],
  formats: {
    'state': {
      textType:'text',
      typeFormat: QueueRoomModel.getStateType,
      labelFormat: QueueRoomModel.getStateLabel
    },
    'updateTime': {
      labelFormat:  (val) =>formatDate(val)
    },
    'action': {
      items: [
        {label: '编辑',elType:'button', value: 'edit', atClick: (data: QueueRoomModel) => onOpenDialog(data)},
        {label: '删除',elType:'button', value: 'delete',  confirm: {title: '您确定要删除该诊室吗？', atConfirm: (data: QueueRoomModel) => onDeleteCategory(data)}}
      ]
    }
  }
})



onBeforeMount(() => {
  getCategoryList()
  getCheckCategoryList()
})

const getCheckCategoryList = () => {
  YjCategoryApi.listYjCategory().then(res => {
    listCheckCategory.value = res.map(item => Object.assign({label: item.name, value: item.id}))
    const checkCategoryField = dialog.formFields.find(item => item.field === 'checkCategory')
    checkCategoryField.options = listCheckCategory.value
  })
}
const getCategoryList = () => {
  table.isLoading = true
  RoomApi.listRegRoom().then((data) => {
    table.data = data
    if(data?.length) {
      selectedRoom.value = data[0]
      onSelectRoom(data[0])
    }
    table.isLoading = false
  }, () => {
    table.isLoading = false
  })
}

const onOpenDialog = (data?: QueueRoomModel) => {
  widgetFormDialogRef.value.onShowDialog(data)
  nextTick(() => {
    if (data.checkCategory) {
      const ccFiled = dialog.formFields.find(item => item.field === 'checkCategory')
      ccFiled.initVal = data.checkCategory.split(",")
      widgetFormDialogRef.value.setFieldValue('checkCategory', data.checkCategory.split(","))
    }
    if (data.patientSource) {
      const ccFiled = dialog.formFields.find(item => item.field === 'patientSource')
      ccFiled.initVal = data.patientSource.split(",")
      widgetFormDialogRef.value.setFieldValue('patientSource', data.patientSource.split(","))
    }
  })
}

const onDeleteCategory = (data: QueueRoomModel) => {
  RoomApi.deleteRegRoom(data.id).then(() => {
    const index = table.data.findIndex(item => item.id === data.id);
    table.data.splice(index, 1)
  })
}

const onEditCallback = (data: QueueRoomModel) => {
  const index = table.data.findIndex(item => item.id === data.id);
  if (index < 0) {
    table.data.push(data)
    table.paging = Object.assign({}, table.paging, {
      total: table.paging.total + 1
    })
  } else {
    table.data.splice(index, 1, data)
  }
}

const onSelectRoom = (data: QueueRoomModel) => {
  $emit('roomSelected', data)
}
</script>
<style scoped lang="scss">
  .yy-queue-category {}
</style>